package avicit.bdp.dds.server.worker.task;

import avicit.bdp.dds.common.utils.OSUtils;
import avicit.bdp.dds.server.entity.TaskExecutionContext;
import avicit.bdp.dds.server.worker.cache.impl.TaskExecutionContextCacheManagerImpl;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;
import java.util.List;
import java.util.function.Consumer;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {LaunchWindowsProcessTest.MockConfiguration.class})
public class LaunchWindowsProcessTest {
    @Autowired
    ApplicationContext context;

    @Before
    public void setup() {
        //SpringApplicationContext.applicationContext = context ;
    }

    @Test(timeout = 60*1000)
    public void launch() throws Exception {
        if (OSUtils.isWindows()) {
            Consumer<List<String> > logHandle = list ->
            {
                list.forEach(s -> System.out.println(s));
            };
            TaskExecutionContext taskExecutionContext = new TaskExecutionContext() ;
            taskExecutionContext.setExecutePath(System.getProperty("user.dir"));
            taskExecutionContext.setTaskAppId("000") ;
            taskExecutionContext.setTaskName("dd-task");
            taskExecutionContext.setTaskInstanceId("DUMMY");
            taskExecutionContext.setStartTime( new Date() );
            taskExecutionContext.setTaskTimeout(1000 * 30 ) ;
            taskExecutionContext.setLogPath("c:/tmp/t.log");


            ShellCommandExecutor shellCommandExecutor = new ShellCommandExecutor(logHandle,
                    taskExecutionContext,
                    LoggerFactory.getLogger("launchTest"));

            CommandExecuteResult result = shellCommandExecutor.run("echo Launched") ;
            Assert.assertTrue("Process not launched", result.getExitStatusCode() == 0);
        }
    }

    @Configuration
    public static class MockConfiguration {
        @Bean
        public TaskExecutionContextCacheManagerImpl taskExecutionContextCacheManager() {
            return new TaskExecutionContextCacheManagerImpl();
        }
    }
}
